﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Workflow.ComponentModel;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.Workflow;
using System.Workflow.ComponentModel.Compiler;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.Sdk.Query;

namespace CrmContrib.Workflow.Activities.Communications
{
    [CrmWorkflowActivity("Send Existing E-mail", "CrmContrib \\ Communications")]
    public class SendExistingEmailActivity : Activity
    {
        [CrmInput("E-mail")]
        [CrmReferenceTarget("email")]
        [ValidationOption(ValidationOption.Required)]
        public Lookup Email
        {
            get { return (Lookup)base.GetValue(EmailProperty); }
            set { base.SetValue(EmailProperty, value); }
        }

        public static readonly DependencyProperty EmailProperty = DependencyProperty.Register("Email", typeof(Lookup), typeof(SendExistingEmailActivity));

        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            var contextService = executionContext.GetService<IContextService>();
            var workflowContext = contextService.Context;
            var service = workflowContext.CreateCrmService();

            var trackingToken = this.GetTrackingToken(service, this.Email.Value);
            
            var request = new SendEmailRequest();
            request.EmailId = this.Email.Value;
            request.TrackingToken = trackingToken;
            request.IssueSend = true;

            service.Execute(request);

            return base.Execute(executionContext);
        }

        private string GetTrackingToken(ICrmService service, Guid emailID)
        {
            var emailEntity = service.Retrieve("email", this.Email.Value, new AllColumns()) as email;
            var request = new GetTrackingTokenEmailRequest();
            request.Subject = emailEntity.subject;

            var response = service.Execute(request) as GetTrackingTokenEmailResponse;
            var trackingToken = response.TrackingToken;

            return trackingToken;
        }
    }
}
